﻿# -*- coding: utf-8 -*-

import datetime
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import webapp2
import urllib
from bs4 import BeautifulSoup
from google.appengine.ext import ndb
from DB.DB_Classes import *
from google.appengine.api import mail
from HTMLParser import HTMLParser
import urllib2
import DB.DbSearchQueries


# Including the models:
from models.getRelevantInfo import *
 

# Including optimizer library
from controllers.optimizerMockSolver import *

# We are using django's simplejson
# module to format JSON strings:
from django.utils import simplejson
import json
import cgi


# The AJAX controllers:
class getFacultiesAndDepartments(webapp2.RequestHandler):
    def get(self):
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        results = getFacultiesAndDeparts(currUniversity,currSemester)
          
        self.response.out.write(results)
          
class getAllCoursesOfSemester(webapp2.RequestHandler):
    def get(self):
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        
        results = getAllCoursesOfSem(currSemester,currUniversity)
        self.response.out.write(results)

class getCoursesListByDept(webapp2.RequestHandler):

    def get(self):
        deptNum = self.request.get('dept_num')
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        results = getCoursesListByDepart(currUniversity,currSemester,deptNum)

        self.response.out.write(results)
         
         
class getCoursesListByDeptAndDay(webapp2.RequestHandler):

    def get(self):
        dayStr = self.request.get('day_str')
        deptNum = self.request.get('dept_num')
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        results = getCoursesListByDepartAndDay(currUniversity,currSemester,deptNum,dayStr)
        
        self.response.out.write(results)
         
         
class getChosenCoursesInforamtion(webapp2.RequestHandler):

    def get(self):
        chosenCoursesList = self.request.get_all('courses_list')
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        
        results = getChosenCoursesInfo(currUniversity,currSemester,chosenCoursesList)
        
        self.response.out.write(results)

class getCourseProfileInfo(webapp2.RequestHandler):
    
    def get(self):
        course_num = self.request.get('course_num')
        department = self.request.get('department')
        currSemester = self.request.get('semester')
        currUniversity = self.request.get('university')
        
        results = getCourseProfileInformationFromModels(currUniversity,currSemester,department,course_num)
        self.response.out.write(results)


class DownloadParseUrl(webapp2.RequestHandler):
    @ndb.toplevel
    def get(self):
        course_num = self.request.get('course_num')
        currUniversity = self.request.get('university')
        s = getCourseSyllabus(currUniversity, course_num)
        if s == "":
            #download HTML file from specified URL
            opener = urllib.FancyURLopener({})
            url = "http://www2.tau.ac.il/yedion/syllabus.asp?course="+str(course_num)+"&year="+DbSearchQueries.get_recent_year()
            try:
                f = opener.open(url)
                content = f.read()
                f.close()
                #get text from HTML
                clean_text = BeautifulSoup(content).get_text()
                index = clean_text.find(u"סילבוס מקוצר")
            except:
                index = -2
            
            if (index==-1):
                    new = u"לא נמצא סילבוס לקורס"
            else:
                if (index==-2):
                    new = u"זמנית לא ניתן לגשת לסילבוס הקורס"
                else:
                    s = clean_text[index+12:]
                    new = s.replace('\n','<br/>')
                    univ =n_University.get_by_id(currUniversity)
                    logging.info("read-4-DownloadParseUrl")
                    course = n_Course_syllabus(id= "syl_"+course_num, course_num = course_num, syllabus = new,parent = univ.key)
                    logging.info("write-4-DownloadParseUrl")
                    course.put_async()

        #build Json and send syllabus back to GUI
        else:
            new = s
        s1 = []
        s1.append({"syl": new})
        jsonStr1 = simplejson.dumps({
                "syllabus"  : s1
         })
       
        self.response.out.write(jsonStr1)

class getOptimizedSchedule(webapp2.RequestHandler):
    def post(self):
        
        jsonParamObj = json.loads(cgi.escape(self.request.body))
        
        result = solver(jsonParamObj[0],jsonParamObj[1])
        
        jsonOptStr = json.dumps({
               "optimizedSchedual"  : result
        })
        
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.write(jsonOptStr)

#add array of havura on top of groups
#first group is RASHI and afterwards it is sorted by group num
class getTableBids2(webapp2.RequestHandler):
    
    def get(self):
        course_num = self.request.get('course_num')
        department = self.request.get('department')
        currUniversity = self.request.get('university')
        results = getCourseBidding(currUniversity,department,course_num)
        self.response.out.write(results)
                  
class saveFacebookId(webapp2.RequestHandler):
    def get(self):
        userGoogleId = self.request.get('googleId')
        userFacebookId = self.request.get('facebookId')
        University = self.request.get('university')
        result = saveFBGoogle(University,userFacebookId,userGoogleId)
        self.response.out.write('success')      
       
        
class getFacebookFriendsByCourse(webapp2.RequestHandler):
    def post(self):
        
        jsonFriendsObj = json.loads(cgi.escape(self.request.body))
        University = jsonFriendsObj[0]
        currSemester = jsonFriendsObj[1]
        departNum = jsonFriendsObj[2]
        courseNum = jsonFriendsObj[3]
        friendsList = jsonFriendsObj[4]
        result = getFriendList(University,currSemester,departNum,courseNum,friendsList)
       
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.write(result)        
 
class getFacrbookFriendChosenCourses(webapp2.RequestHandler):
    def get(self):
        userFacebookId = self.request.get('facebookId')
        currUniversity = self.request.get('university')

        courses_list = getFriendChosenCourses(currUniversity, userFacebookId)
        self.response.out.write(courses_list)             
        
              
class saveUserScheduleData(webapp2.RequestHandler):
    def post(self):
        jsonToSaveObj = json.loads(cgi.escape(self.request.body))
        University = jsonToSaveObj[0]
        userId = jsonToSaveObj[1]
        userEmail = jsonToSaveObj[2]
        nickName = jsonToSaveObj[3]
        info = jsonToSaveObj[4]
        semesterToSave = jsonToSaveObj[5]
        chosenCoursesLists = jsonToSaveObj[6]
        saveUserData(University, userId, userEmail, nickName,info,semesterToSave,chosenCoursesLists)
        
        self.response.out.write('success')
        
class loadUserScheduleData(webapp2.RequestHandler):
    def get(self):
        University = self.request.get('university')
        userId = self.request.get('user_id')
        userEmail = self.request.get('user_email')
        nickName = self.request.get('nick_name')
       
        loadResult = loadUserData(University, userId, userEmail, nickName)
       
        self.response.out.write(loadResult)        
                                                  
class submitSupportMail(webapp2.RequestHandler):
    def get(self):
        mailSubject = self.request.get('subject')
        mailBody = self.request.get('body')
        fromName = self.request.get('fromName')
        fromMailTxt = self.request.get('fromMailTxt')
        fromMail = self.request.get('fromMail')
        toMail = self.request.get('toMail')
        mail.send_mail(sender="<"+fromMail+">",
                       to="<"+toMail+">",
                       subject=mailSubject,
                       body=""+"Mail from: "+fromName+"\n"+"Email: "+fromMailTxt+"\n"+"Mail body: "+mailBody+"")
        
        #success
        jsonResult = json.dumps({
               "response"  : "1"
        })
        self.response.out.write(jsonResult)
        

                
class getOldExamsLinks(webapp2.RequestHandler):
        def get(self):
                
                userId = self.request.get('userId')
                currUniversity = self.request.get('currUniversity')
                eventsToDelete = getEventsToDelete(currUniversity,userId)
                if(eventsToDelete==None):
                        eventsToDelete = [[],[],[]] 
                
                jsonResult = json.dumps({
                    "response"  : eventsToDelete
                })
                self.response.out.write(jsonResult)
                
class saveNewEvents(webapp2.RequestHandler):
        def post(self):
                jsonToSyncData = json.loads(cgi.escape(self.request.body))
                currUniversity = jsonToSyncData[0]
                userId = jsonToSyncData[1]
                userEmail = jsonToSyncData[2]
                userNickname = jsonToSyncData[3]
                eventsToSave = jsonToSyncData[4]
                
                saveEventsSynced(currUniversity,userId,eventsToSave,userEmail,userNickname)
                
                jsonOptStr = json.dumps({
                "response"  : '1'
                })
                self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
                self.response.write(jsonOptStr)